package com.authine.cloudpivot.web.api.secondopen.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.secondopen.domain.AjaxResult;
import com.authine.cloudpivot.web.api.secondopen.domain.SharedPoolParameter;
import com.authine.cloudpivot.web.api.secondopen.domain.TableObj;
import com.authine.cloudpivot.web.api.secondopen.modules.SharedPoolDeatailVO;
import com.authine.cloudpivot.web.api.secondopen.service.SharedPoolService;
import com.authine.cloudpivot.web.api.secondopen.utils.PageUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(value = "二开接口",tags = "共享池控制器")
@RestController
@RequestMapping("/api/sharedpool")
public class SharedPoolController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SharedPoolController.class);

    @Autowired
    private SharedPoolService sharedPoolService;


    /**
     * 领取单据
     */
    @PostMapping("/receivetask")
    public AjaxResult updateStatus(@RequestBody  List<SharedPoolParameter> list){
        log.info("获取参数：list={}",JSON.toJSONString(list));
        if (CollectionUtils.isEmpty(list)){
            return AjaxResult.error("参数为空，领取失败");
        }
        String tablehead = "iusi6_";
        String tablename=null;
        for (int i = 0; i < list.size(); i++) {
            SharedPoolParameter sharedPool = list.get(i);
            //用户id
            String id = sharedPool.getId();
            //表单id
            String objId = sharedPool.getObjId();
            //数据表名
            tablename = sharedPool.getProcode();
            //共享池数据状态
            String status = sharedPool.getStatus();
            if (StringUtils.isEmpty(objId)||StringUtils.isEmpty(tablehead+tablename)){
                return AjaxResult.error("业务对象id为空或表名为空");
            }

            String seqNo = sharedPool.getSeqno();
            //判断当前共享池数据状态
            String result = sharedPoolService.selectDataStatus(objId, seqNo);
            if ("已领取".equals(result)){
                return AjaxResult.error(seqNo+"已被他人领取");
            }
            Map map=new HashMap();
            map.put("id",id);
            map.put("type",3);
            JSONArray jsonArray=new JSONArray();
            jsonArray.add(map);
            String lqr = jsonArray.toString();
            //设置领取人
            sharedPoolService.setlqr(tablehead+tablename,objId,lqr);
            //修改流程的状态
            sharedPoolService.updateStatus(tablehead+tablename,objId,status);
            //修改单据在共享池中的状态
            sharedPoolService.updatePool(objId,sharedPool.getProcode(),status);
        }
        return AjaxResult.success();
    }

    /**
     * 表单提交后，加入共享池
     */
    @PostMapping("/getTableinfo")
    public AjaxResult getTableInfo(String objId,String processCode){
        log.info("获取参数:objId={},processCode={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("参数不完整，直接结束");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }


        //表单id
        String id = bizObject.getId();
        //流程名称
        String name = bizObject.getName();
        //流程id
        String workflowInstanceId = bizObject.getWorkflowInstanceId();
        //发起人
        String creater = bizObject.getCreater().getName();
        //发起时间
        Date createdTime = bizObject.getCreatedTime();
        //单据号
        String sequenceNo = bizObject.getSequenceNo();
        //领取状态
        String lqzt = bizObject.getString("lqzt");

        //判断共享池中是否存在
        String result = sharedPoolService.selectData(objId, sequenceNo);
        if (!"N".equals(result)){
            return AjaxResult.error("共享池中已存在"+sequenceNo+"，加入失败");
        }
        TableObj tableObj = new TableObj();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        tableObj.setId(uuid);
        tableObj.setBdid(id);
        tableObj.setName(name);
        tableObj.setCreater(creater);
        tableObj.setCreatetime(createdTime);
        tableObj.setSequenceNo(sequenceNo);
        tableObj.setClaimstatus(lqzt);
        tableObj.setProcode(processCode);
        tableObj.setWorkflowInstanceId(workflowInstanceId);
        sharedPoolService.insertData(tableObj);
        return  AjaxResult.success("插入共享池成功");
    }

    /**
     * 获取共享池中的数据
     * @return
     */
    @GetMapping("/getsharedpool")
    @ApiOperation(value = "获取共享池数据",notes = "获取共享池数据")
    public ResponseResult<SharedPoolDeatailVO> getSharedPool(
            @RequestParam(value = "pageNum",required = false) Integer pageNum,
            @RequestParam(value = "pageSize",required = false) Integer pageSize,
            @RequestParam(value = "processName",required = false) String processName,
            @RequestParam(value = "sequenceNo",required = false) String sequenceNo){
        List<TableObj> tableObjs = sharedPoolService.getSharedPool(processName,sequenceNo);
        SharedPoolDeatailVO sharedPoolDeatailVO = new SharedPoolDeatailVO();
        sharedPoolDeatailVO.setTotal(tableObjs.size());
        if(CollectionUtils.isNotEmpty(tableObjs)){
            sharedPoolDeatailVO.setTableObjs(PageUtil.startPage(tableObjs,pageNum+1,pageSize));
        }else{
            sharedPoolDeatailVO.setTableObjs(new ArrayList<>());
        }
        return getOkResponseResult(sharedPoolDeatailVO, "获取信息成功");
    }

    /**
     * 流程结束后修改共享池状态为已结束
     */
    @PostMapping("/deleteShared")
    public AjaxResult deleteSharedPoolProcess(String objId,String processCode){
        log.info("获取参数:objId={},processCode={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("参数不完整，直接结束");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }

        String sequenceNo = bizObject.getSequenceNo();
        //判断共享池中该数据是否存在
//        String result = sharedPoolService.selectData(objId, sequenceNo);
//        if ("N".equals(result)){
//            return AjaxResult.error("共享池中不存在"+sequenceNo);
//        }
        sharedPoolService.deleteSharedPool(objId,sequenceNo);
        return AjaxResult.success("单据"+sequenceNo+"已从共享池删除");
    }

    /**
     * 放回共享池
     */
    @PostMapping("/rejecttasks")
    public AjaxResult  rejectTasks(String objId,String processCode){
        log.info("获取参数:objId={},processCode={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("参数不完整，直接结束");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        String result = sharedPoolService.selectData(objId, null);
        if (!"N".equals(result)){
            return AjaxResult.error("共享池中已存在该数据"+"ID:"+result);
        }
        //先修改流程实例的领取状态
        String tablename="iusi6_"+processCode;
        sharedPoolService.updateStatus(tablename,objId,"未领取");
        //删除领取人
        sharedPoolService.setlqr(tablename,objId,null);
        //修改共享池中的状态
        sharedPoolService.updatePool(objId,processCode,"未领取");
        //删除token表中finishtime为空，state=unfinished的数据，并修改activitytype=SYSTEM_ACTIVITY的state=unfinished
        String workflowInstanceId = bizObject.getWorkflowInstanceId();
        sharedPoolService.deleteWorkToken(workflowInstanceId);
        sharedPoolService.updateSystemActivity(workflowInstanceId);
        //删除待办表中的待办任务
        sharedPoolService.deleteToDoTasks(workflowInstanceId);
        return AjaxResult.success();
    }

    /**
     * 驳回时触发
     */
    @PostMapping("/trionrej")
    public  AjaxResult bhs(String objId,String processCode,String activity){
        //零修件申请
        String[] arr={"Activity2","Activity3","Activity5","Activity6","Activity7","Activity39","Activity40"};
        //部门申请书B
        String[] arr2={"Activity2","Activity5","Activity6","Activity9","Activity8"};
        //
        String[] arr3={""};
        Boolean flag=null;
        if ("lxjsq".equals(processCode)){
            flag = Arrays.asList(arr).contains(activity);
        }
        if ("bmsqsB".equals(processCode)){
            flag = Arrays.asList(arr2).contains(activity);
        }
        //判断是否在共享池前
        if (flag){
            //驳回到共享池前，需要改变状态
            //先修改流程实例的领取状态
            String tablename="iusi6_"+processCode;
            //sharedPoolService.updateStatus(tablename,objId,"未领取");
            //修改共享池中的状态
            sharedPoolService.updatePool(objId,processCode,"未领取");
            return AjaxResult.success("流程已驳回到共享池");
        }else {
            return AjaxResult.success("不涉及共享池");
        }
    }

}
